package edu.njfu.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.sql.DataSource;

/**
 * @Author:
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private DataSource dataSource;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().headers().frameOptions().sameOrigin();;

        http.formLogin().loginPage("/login.html").loginProcessingUrl("/login")
                .successHandler(new MyAuthenticationSuccessHandler())
                .failureHandler(new MyAuthenticationFailureHandler())
                .permitAll().and();

        http
                .authorizeRequests()
                .antMatchers("/css/**", "/fonts/**", "/images/**", "/js/**").permitAll()
                .antMatchers("/pages/system/**").hasAnyRole("SYSTEM", "ROOT")
                .antMatchers("/pages/business/**").hasAnyRole("BOOK", "ROOT")
                .anyRequest().authenticated();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("root")
                .password(new BCryptPasswordEncoder().encode("root"))
                .roles("ROOT").and()
                .withUser("cp").password(new BCryptPasswordEncoder().encode("123456"))
                .roles("BOOK").and()
                .withUser("system").password(new BCryptPasswordEncoder().encode("123456"))
                .roles("SYSTEM");

        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select username,password,role_id from bookadmin.user WHERE username=?")
                .authoritiesByUsernameQuery("select username, role.code as authority from role where role.id = (select user.role_id from user where username = ?)")
                .passwordEncoder(new BCryptPasswordEncoder());

    }
}
